package org.jash.mvp2206.news;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;

import org.jash.mvp2206.R;
import org.jash.mvp2206.entity.NewsPage;
import org.jash.mvp2206.entity.TopHot;

import java.util.ArrayList;
import java.util.List;

public class RNewsAdapter extends RecyclerView.Adapter<RNewsAdapter.NewsViewHolder> {
    private List<NewsPage.DataBean.RecordsBean> data = new ArrayList<>();
    private OnClickNewsListener listener;
    @NonNull
    @Override
    public NewsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new NewsViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_news, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull NewsViewHolder holder, int position) {
        NewsPage.DataBean.RecordsBean bean = data.get(position);
        holder.title.setText(bean.getTitle());
        holder.time.setText(bean.getCreateTime());
        Glide.with(holder.image).load(bean.getImgurl()).into(holder.image);
//        holder.itemView.setOnClickListener(v -> Toast.makeText(v.getContext(), bean.getTitle(), Toast.LENGTH_SHORT).show());
        if (listener != null) {
            holder.itemView.setOnClickListener(v -> listener.onClick(bean));
        }
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    public void addAll(List<NewsPage.DataBean.RecordsBean> list) {
        int size = data.size();
        data.addAll(list);
        notifyItemRangeInserted(size, list.size());
    }
    public void clear() {
        int size = data.size();
        data.clear();
        notifyItemRangeRemoved(0, size);
    }

    public void setListener(OnClickNewsListener listener) {
        this.listener = listener;
    }

    public interface OnClickNewsListener {
        void onClick(NewsPage.DataBean.RecordsBean bean);
    }
    public static class NewsViewHolder extends RecyclerView.ViewHolder {
        private ImageView image;
        private TextView title;
        private TextView time;
        public NewsViewHolder(@NonNull View itemView) {
            super(itemView);
            image = itemView.findViewById(R.id.image);
            title = itemView.findViewById(R.id.title);
            time = itemView.findViewById(R.id.time);
        }
    }
}
